package cn.yotta.user.core.server.iface.login.impl;

import cn.yotta.user.api.params.login.BaseLoginByPasswordRequest;
import cn.yotta.user.core.server.dto.captcha.CaptchaCheckDto;
import cn.yotta.user.core.server.dto.user.UserDto;
import cn.yotta.user.core.server.iface.login.PasswordEncoder;
import cn.yotta.user.core.server.manager.captcha.CaptchaManager;
import cn.yotta.user.web.autoconfiguration.exception.UserLoginException;

import static cn.yotta.user.api.error.PasswordErrorCode.PASSWORD_NOT_MATCH;

/**
 * @author wyaoyao
 * @date 2023/3/9 15:35
 * 抽象密码登录策略
 */
public abstract class AbstractPasswordLoginProvider<T extends BaseLoginByPasswordRequest> extends AbstractLoginProvider<T> {

    private final PasswordEncoder passwordEncoder;

    private final CaptchaManager captchaManager;

    private final Boolean skipCheck;

    protected AbstractPasswordLoginProvider(PasswordEncoder passwordEncoder, CaptchaManager captchaManager, Boolean skipCheck) {
        this.passwordEncoder = passwordEncoder;
        this.captchaManager = captchaManager;
        this.skipCheck = skipCheck;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDto user, T request) {
        // 校验用户名和密码
        if (!passwordEncoder.matches(this.getCredentials(request), user.getPassword())) {
            throw new UserLoginException(PASSWORD_NOT_MATCH.getCode());
        }
    }

    /**
     * 完成对图片验证验证码的校验
     */
    @Override
    protected void preLoadUser(T request) {
        if (this.skipCheck) {
            return;
        }
        final String captchaToken = request.getCaptchaToken();
        captchaManager.checkCaptcha(CaptchaCheckDto.builder()
                .token(captchaToken)
                .value(request.getCaptcha())
                .build());

    }
}
